package com.orchid.community.models.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orchid.community.common.exceptions.CustomException;
import com.orchid.community.common.utils.CodeEnum;
import com.orchid.community.common.utils.MsgResponse;
import com.orchid.community.common.utils.ResultUtils;
import com.orchid.community.common.weixin.WeiXinConfig;
import com.orchid.community.models.DTO.MissionDto;
import com.orchid.community.models.DTO.UserInfoDTO;
import com.orchid.community.models.entity.Mission;
import com.orchid.community.models.entity.User;
import com.orchid.community.models.mapper.AppletUserMapper;
import com.orchid.community.models.mapper.MissionMapper;
import com.orchid.community.models.mapper.TagsMapper;
import com.orchid.community.models.service.AppletUserService;
import com.orchid.community.models.service.TagsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AppletUserServiceImpl implements AppletUserService {

    @Autowired
    private AppletUserMapper appletUserMapper;

    @Autowired
    private TagsMapper tagsMapper;

    @Autowired
    private MissionMapper missionMapper;

    @Override
    public MsgResponse login(Map<String, Object> map) {
        String jsCode = (String) map.get("jsCode");
        RestTemplate restTemplate = new RestTemplate();
        String requestUrl = WeiXinConfig.WX_LOGIN_URL + "?appid=" + WeiXinConfig.APPID + "&secret=" + WeiXinConfig.AppSecret + "&js_code=" + jsCode + "&grant_type=authorization_code";

        try {
            String response = restTemplate.getForObject(requestUrl, String.class);
            log.info("请求结果：" + response);
            JSONObject responseObject = JSON.parseObject(response);
            String openid = responseObject.get("openid").toString();
            User user = appletUserMapper.selectByOpenId(openid);
            if(user == null){
                User newUser = new User();
                newUser.setOpenId(openid);
                newUser.setCreateDate(LocalDateTime.now());
                appletUserMapper.insert(newUser);
                return ResultUtils.success(newUser.getUserId());
            }else {
                user.setCreateDate(LocalDateTime.now());
                appletUserMapper.updateById(user);
                return ResultUtils.success(user.getUserId());
            }
        } catch (RestClientException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public MsgResponse getMissionList(MissionDto missionDto) {
        //产出改用户的所有标签
        List<String> tagsList = tagsMapper.getTagsByUserId(String.valueOf(missionDto.getParam().getUserId()));
        //获取所有的服务列表
        List<Mission> missionList = missionMapper.getMissionList(missionDto.getParam());
        List<Mission> filteredList = missionList.stream()
                .filter(mission -> {
                    if (mission.getDispatch() == 1) {
                        List<String> scopList = Arrays.asList(mission.getScope().split(","));
                        return tagsList.containsAll(scopList);
                    } else if (mission.getDispatch() == 0) {
                        List<String> scopList = Arrays.asList(mission.getScope().split(","));
                        return !tagsList.containsAll(scopList);
                    }
                    return true;
                }).collect(Collectors.toList());
        int start = (missionDto.getPageNo() - 1) * missionDto.getPageSize();
        int end = Math.min(start + missionDto.getPageSize(), filteredList.size());
        List<Mission> pagedContent = (start < filteredList.size()) ? filteredList.subList(start, end) : new ArrayList<>();
        // 创建结果Map
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("count", filteredList.size());
        resultMap.put("list", pagedContent);
        return ResultUtils.success(resultMap);
    }


}
